<template>
  <basic-dialog :visible="show"
                title="设置工位"
                min-width="720px"
                :isFullScreen="false"
                :hasFooterMargin="false"
                :isShowInnerLoading="isSubmitting"
  >
    <q-form class="dialog-content" @submit.prevent="_submit">
      <div class="flex justify-between margin-20">
        <!-- 左侧 -->
        <q-card class="left side margin-r-20 scroll-box" flat bordered>
          <div style="padding: 0 10px 10px"
               :style="{'padding-top': index ? 0 : '10px'}"
               v-for="(user, index) in users"
               :key="index">
            <q-chip
              clickable
              :removable="users.length > 1"
              outline
              square
              color="primary"
              text-color="black"
              :label="user.number + ' - ' + user.name"
              @remove="users.splice(index, 1)"
            />
            <q-tooltip>{{user.number}}-{{user.name}}</q-tooltip>
          </div>
        </q-card>

        <!-- 右侧 -->
        <q-card class="right side scroll-box" flat bordered>
          <q-card-section>
            <q-tree
              :nodes="orgNodes"
              node-key="uniqueKey"
              tick-strategy="leaf-filtered"
              :ticked.sync="selectedNodesKeys"
              default-expand-all
            />
          </q-card-section>
        </q-card>
      </div>

      <!-- 底部按钮 -->
      <q-separator />
      <div class="dialog-footer text-center margin-t-10">
        <q-btn class="q-mr-md" outline label="取消" color="primary" @click="$emit('close')" />
        <q-btn
          label="确认"
          color="primary"
          unelevated
          type="submit"
          :loading="isSubmitting"
        />
      </div>
    </q-form>
  </basic-dialog>
</template>

<script>
import { listWorkCentersTree } from 'src/boot/common/tree'
import userManageApi from 'src/boot/system/user-manage'
import { defaultSchemesClearer } from 'src/assets/js/util'

export default {
  name: 'work-center-setting',
  props: {
    /**
     * 显示 dialog
     * default: false
     * required
     */
    show: {
      type: Boolean,
      default: false,
      required: true
    },

    /**
     * 选中的用户对象数组
     */
    selectedUsers: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      // form 正在提交
      isSubmitting: false,

      // 用户对象数组
      users: [],

      // 多层组织节点
      orgNodes: [],

      // 选中的节点的 unique key
      selectedNodesKeys: []
    }
  },
  methods: {
    /**
     * 列举工位 tree
     * @private
     */
    _listWorkCenters: function () {
      listWorkCentersTree().then(resp => {
        // 去除 default 节点
        let clearTree = defaultSchemesClearer.clear(resp)

        // 重新组织 tree
        clearTree.forEach(reorganize)

        function reorganize (node) {
          // 如果当前节点是工位，将 opdesc & opname 挪到 label
          // opdesc = 工位名称，opname = 工位编号
          if (node.level === 5) {
            node.label = node.opdesc + ' (' + node.opname + ')'
          }

          // 为节点添加唯一键，用于 tree 组件标识唯一节点
          node.uniqueKey = node.level + ':' + node.id

          if (node.children instanceof Array) {
            node.children.forEach(reorganize)
          }
        }

        this.orgNodes = clearTree
      })
    },

    /**
     * 勾选所有用户共有的工位
     * @private
     */
    _checkMutualWorkCenters: function () {
      userManageApi.listUsersWorkCenters(this.userIds)
        .then(resp => {
          let users = resp.data

          if (users.length === 0) {
            return
          }

          // 取所有用户 work center ID 的交集
          let intersection = users[0].workCenterIds
          for (let i = 1; i < users.length; i++) {
            let workCenterIds = users[i].workCenterIds
            intersection = intersection.filter(o => workCenterIds.includes(o))
          }

          // 勾选
          // push 而不是直接覆盖，避免 API 请求慢时，已勾选的工位被交集覆盖
          let arr = this.selectedNodesKeys.slice()
          arr.push(...intersection.map(o => '5:' + o))
          this.selectedNodesKeys = [...new Set(arr)]
        })
    },

    /**
     * 提交 form
     * @private
     */
    _submit: function () {
      this.isSubmitting = true

      // 发送请求
      userManageApi.setUsersWorkCenters(this.userIds, this.selectedWorkCenterIds)
        .then(() => {
          this.$emit('submitted')
        })
        .finally(() => {
          this.isSubmitting = false
        })
    }
  },
  computed: {
    // 平坦化的组织节点
    flattenedOrgNodes: function () {
      let flatArr = []

      // 递归平坦化每一级节点
      this.orgNodes.forEach(flattenNode)

      function flattenNode (node) {
        flatArr.push(Object.assign({}, node, { children: undefined }))

        if (node.children instanceof Array) {
          node.children.forEach(flattenNode)
        }
      }

      return flatArr
    },

    // 选中的工位
    // 从所有选中的组织 node 中筛选出 level = 5 的项
    selectedWorkCenterIds: function () {
      return this.flattenedOrgNodes
        .filter(node => this.selectedNodesKeys.includes(node.uniqueKey))
        .filter(node => node.level === 5)
        .map(node => node.id)
    },

    // 用户 ID 数组
    userIds: function () {
      return this.users.map(user => user.id)
    }
  },
  watch: {
    // 选中的用户
    selectedUsers: function (newVal) {
      // 从 props clone 到 data
      this.users = Object.assign([], newVal)
    },

    // 显隐状态
    show: function (newVal) {
      if (newVal) {
        // 显示时，勾选所有用户共有的工位
        this._checkMutualWorkCenters()
      } else {
        // 隐藏时，清空已选的工位
        this.selectedNodesKeys = []
      }
    }
  },
  created () {
    this._listWorkCenters()
  }
}
</script>

<style scoped lang="stylus">
  .side {
    height 482px
    overflow auto

    &.left {
      width 200px

      .inner-box {
        display flex
        flex-direction column
      }
    }

    &.right {
      width 460px
    }
  }
  >>>.q-chip {
    height 32px !important
    justify-content space-between
    margin 4px 0 !important
    max-width 100% !important
    width 100% !important

    &:first-child {
      margin-top: 0 !important
      max-width 100% !important
    }

    &:last-child {
      margin-bottom: 0 !important
    }

    &:focus {
      box-shadow none !important
    }

    .q-chip__content{
      color #000 !important
      line-height 32px !important
      display: block;
      word-break: keep-all;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .q-chip__icon--remove {
      margin-right -0.2em !important
      color #000 !important
      line-height 32px !important
    }
  }
  >>>.q-checkbox--dense{
    &:focus:not(.disabled){
      .q-checkbox__inner:before{
        transform: scale3d(1.8, 1.8, 1.8) !important
      }
    }
  }
</style>
